#include <iostream>
#include <sstream>
#include "logging.h"

namespace custom {
// 获取单例实例
Logging &Logging::getInstance() {
    static Logging instance;
    return instance;
}

// 设置日志回调
void Logging::setLoggerCallback(std::function<void(int, const std::string &, int, const std::string &)> callback) {
    logCallback = callback;
}

// 打印日志
void Logging::log(int level, const std::string &file, int line, const std::string &msg) {
    if (logCallback) {
        logCallback(level, file, line, msg);
    } else {
        // 默认日志处理
        std::cerr << "[Level " << level << "] " << file << ":" << line << " - " << msg << std::endl;
    }
}

class LogMessageImpl {
public:
    LogMessageImpl(int level, const char *file, int line)
        : level_(level), logger_(Logging::getInstance()), file_(file == nullptr ? "" : file), line_(line) {}
    ~LogMessageImpl() { logger_.log(level_, file_, line_, os.str()); }

public:
    std::ostringstream os;

private:
    Logging &logger_;
    int level_;
    std::string file_;
    int line_;
};

LogMessage::LogMessage(int level, const char *file, int line) : impl_(new LogMessageImpl(level, file, line)) {}

LogMessage::~LogMessage() {
    if (impl_) {
        delete impl_;
        impl_ = nullptr;
    }
}

std::ostream &LogMessage::Os() { return impl_->os; }

} // namespace custom